﻿using System;
using System.Diagnostics.Contracts;
using System.Windows.Data;

namespace AnthStat.WPF.Applications.Converters
{
    [ValueConversion(typeof(double), typeof(double))]
    public sealed class InchesToCentimetersConverter : IValueConverter
    {
        private const double INCHES_TO_CM = 2.54;
        private const double CM_TO_INCHES = 0.39370079;

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || String.IsNullOrEmpty(value.ToString())) return null;
            double length = System.Convert.ToDouble(value);

            if (Double.IsNaN((length)))
            {
                return null;
            }

            Contract.Assert(length >= 0);

            return Math.Round(length * CM_TO_INCHES, 2);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || String.IsNullOrEmpty(value.ToString())) return Double.NaN;

            double length = System.Convert.ToDouble(value);
            Contract.Assert(length >= 0);

            return Math.Round(length * INCHES_TO_CM, 2);
        }
    }
}
